package data

import (
	"context"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"fmt"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"

	"go-skeleton/app/v1/service/internal/conf"
	"go-skeleton/app/v1/service/internal/data/ent"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-redis/redis/extra/redisotel"
	"github.com/go-redis/redis/v8"
	"github.com/google/wire"

	_ "github.com/go-sql-driver/mysql"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewDB, NewRedis, NewUserRepo)

// Data .
type Data struct {
	db  *ent.Client
	rdb *redis.Client
}

// NewData .
func NewData(c *conf.Data, logger log.Logger, db *ent.Client, rdb *redis.Client) (*Data, func(), error) {
	cleanup := func() {
		log.NewHelper(logger).Info("closing the data resources")
	}
	return &Data{
		db:  db,
		rdb: rdb,
	}, cleanup, nil
}

func NewDB(c *conf.Data) (*ent.Client, func(), error) {
	drv, err := sql.Open(
		c.Database.Driver,
		c.Database.Source,
	)
	sqlDrv := dialect.DebugWithContext(drv, func(ctx context.Context, i ...interface{}) {
		if c.Database.Debug {
			log.Info(i...)
			tracer := otel.Tracer("ent.")
			kind := trace.SpanKindServer
			_, span := tracer.Start(ctx,
				"Query",
				trace.WithAttributes(
					attribute.String("sql", fmt.Sprint(i...)),
				),
				trace.WithSpanKind(kind),
			)
			span.End()
		}
	})
	client := ent.NewClient(ent.Driver(sqlDrv))
	if err != nil {
		log.Errorf("failed opening connection to sqlite: %v", err)
		return nil, nil, err
	}
	cleanup := func() {
		if err = client.Close(); err != nil {
			log.Error(err)
		}
	}

	return client, cleanup, nil
}

func NewRedis(c *conf.Data) (*redis.Client, func(), error) {
	rdb := redis.NewClient(&redis.Options{
		Addr:         c.Redis.Addr,
		Password:     c.Redis.Password,
		DB:           int(c.Redis.Db),
		DialTimeout:  c.Redis.DialTimeout.AsDuration(),
		WriteTimeout: c.Redis.WriteTimeout.AsDuration(),
		ReadTimeout:  c.Redis.ReadTimeout.AsDuration(),
	})
	cleanup := func() {
		if err := rdb.Close(); err != nil {
			log.Error(err)
		}
	}
	rdb.AddHook(redisotel.TracingHook{})
	return rdb, cleanup, nil
}
